package com.itheima.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.itheima.mapper.UmsAdminRoleRelationMapper;
import com.itheima.pojo.UmsAdminRoleRelation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UmsAdminRoleRelationImpl implements UmsAdminRoleRelationApi {
    @Autowired
    private UmsAdminRoleRelationMapper mapper;

    @Override
    public List<Long> getAdminRoleId(Long id) {
        List<UmsAdminRoleRelation> umsAdminRoleRelations
                = mapper.selectList(new LambdaQueryWrapper<UmsAdminRoleRelation>().eq(UmsAdminRoleRelation::getAdminId, id));
        if (CollUtil.isEmpty(umsAdminRoleRelations)) return new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        for (UmsAdminRoleRelation umsAdminRoleRelation : umsAdminRoleRelations) {
            ids.add(umsAdminRoleRelation.getRoleId());
        }
        return ids;
    }

    @Override
    public void save(Integer adminId, List<Integer> roleIds) {
        for (Integer roleId : roleIds) {
            UmsAdminRoleRelation relation = new UmsAdminRoleRelation();
            relation.setAdminId(Long.valueOf(adminId));
            relation.setRoleId(Long.valueOf(roleId));
            mapper.insert(relation);
        }
    }

    @Override
    public void deleteByAdminId(Long userId) {
        mapper.delete(new LambdaQueryWrapper<UmsAdminRoleRelation>().eq(UmsAdminRoleRelation::getAdminId,userId));

    }


    @Override
    public Integer findByRids(ArrayList<Integer> ids) {

        //标记
        int flag = 0;

        for (Integer roleId : ids) {

            LambdaQueryWrapper<UmsAdminRoleRelation> lqw = new LambdaQueryWrapper<>();
            lqw.eq(UmsAdminRoleRelation::getRoleId, roleId);
            List<UmsAdminRoleRelation> list = mapper.selectList(lqw);

            if (ObjectUtils.isNotEmpty(list)) {
                flag = 1;

                for (UmsAdminRoleRelation umsAdminRoleRelation : list) {
                    if (umsAdminRoleRelation.getAdminId() == 3) {
                        flag = 2;
                        return flag;
                    }
                }

            }
        }

        return flag;
    }

    @Override
    public void update(Integer adminId, List<Integer> roleIds) {
        mapper.delete(new LambdaQueryWrapper<UmsAdminRoleRelation>().eq(UmsAdminRoleRelation::getAdminId,adminId));
        for (Integer roleId : roleIds) {
            UmsAdminRoleRelation relation=new UmsAdminRoleRelation();
            relation.setAdminId(Long.valueOf(adminId));
            relation.setRoleId(Long.valueOf(roleId));
            mapper.insert(relation);
        }
    }


}
